package com.sopt.comm.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

public class CommUtil {
	public CommUtil(){
	}
	
	/**
	 * Logger for this class
	 */

	private static final Logger logger = Logger.getLogger(CommUtil.class);
	public static String IMG_WIDTH = "48";
	public static String IMG_HEIGHT = "48";
	public static String PAGE_SIZE = "15";
	
	/*
	 * chkeckLength
	 * 길이 측정 str의 문자열 길이가 min보다 작거나, max보다 크면 false
	 * min < str.length && str.length < max 면 true 리턴
	 */
	public static boolean checkLength(String str,int min, int max){
		boolean result = false;
		if(str.length() > min && str.length() < max)
			result = true;
		return result;
	}
	
	/*
	 * Email 형식 체크
	 * 올바른 이메일이 아닐경우 false 리턴
	 */
	public static boolean isValidEmail(String str) {
		  boolean result = false;
		  String regex = "^[_a-z0-9-]+(.[_a-z0-9-]+)*@(?:\\w+\\.)+\\w+$";

	        Pattern p = Pattern.compile(regex);
	        Matcher m = p.matcher(str);
	        if( m.matches() ) {
	        	result = true; 
	        }
	        return result;
		 }
	/*
	 * md5 생성
	 * 입력 받은 String을 md5 암호화 후 리턴
	 */
	public static String md5(String str){
		StringBuffer sb = new StringBuffer();
		
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(str.getBytes());
			byte[] md5Bytes = md5.digest();
			
			for (int i = 0; i < md5Bytes.length; i++) {
				sb.append(md5Bytes[i]);
			}
		} catch (Exception e) {
		}
		return sb.toString();
	}
	
	/*
	 * XSS방지용 Html Filtering 
	 */
	public static String htmlFiltering(String str){
		str = str.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
		str = str.replaceAll("eval\\((.*)\\)", "");
		str = str.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
		str = str.replaceAll("script", "");
		
		return str;
	}
	public static String addLinkToUrlPattern(String str){
		String regex = "([\\p{Alnum}]+)://([a-z0-9.\\-&/%=?:@#$(),.+;~\\_]+)"; 
				   
		Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); 
		Matcher m = p.matcher(str); 

		String convertedStr = m.replaceAll("<a href='http://$2' target=_blank>http://$2</a>");
		System.out.println(convertedStr);
		return convertedStr;
	}
	
	 /**
	  * 문자열을 받아서 null이면 공백 문자열로 리턴
	  * @param  String str
	  * @return String rtnStr
	  */
	public static String NVL(String str) {
	  if ((str == null) || (str.trim().equals("")) || (str.trim().equals("null")))
	   return "";
	  else
	   return str.trim();
	 }
	
	/**
	  * 문자열이 널이면 대체할 문자열을 리턴
	  * @param  String str
	  * @param  String NVLString
	  * @return String rtnStr
	  */
	public static String NVL(Object str, String NVLString) {
	  if ((str == null) || (str.toString().trim().equals("")) || (str.toString().trim().equals("null")))
	   return NVLString;
	  else
	   return str.toString();
	 }
	
	 /**
	  * 문자열이 널이면 대체할 문자열을 리턴
	  * @param  String str
	  * @param  String NVLString
	  * @return String rtnStr
	  */
	public static String NVL(String str, String NVLString) {
	  if ((str == null) || (str.trim().equals("")) || (str.trim().equals("null")))
	   return NVLString;
	  else
	   return str;
	 }
	
	/**
	  * ArrayList 랜덤화
	  * @param  ArrayList<HashMap> lt
	  * @return ArrayList<HashMap> lt
	  */
	public static ArrayList RandomizeArrayList(ArrayList lt){
		
		Random random = new Random();
		for(int i = lt.size()-1; i >0; --i){
			int cur = random.nextInt(i);
			HashMap hm = (HashMap)lt.get(i);
			lt.set(i, lt.get(cur));
			lt.set(cur, hm);
		}
		
		return lt;
	}
	
	/**
	  * returnUrl을 요청서버주소에 따라 구해준다.(index.jsp)
	  * @param  HttpServletRequest request
	  * @return String url
	  */
	public static String getReturnUrl(HttpServletRequest request){
		String url = request.getServerName()+request.getContextPath()+request.getServletPath();
		if(url.lastIndexOf("index.jsp")!=-1)
			url = url.substring(0, url.lastIndexOf("index.jsp")-1);
		if(url.indexOf("http://")==-1)
			url = "http://"+url;
		return url;
	
	}
	
	public static String getMD5(String source){
		String result = "";
		
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		md.update(source.getBytes());
		byte[] md5Code = md.digest();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < md5Code.length; i++) {
			String md5Char = String.format("%02x", 0xff&(char)md5Code[i]);
			sb.append(md5Char);
		}
		result = sb.toString();
		
		return result;
	}
}
